package com.eonmind.knowledge.mapper;

import com.eonmind.common.contract.data.base.BaseMongoMapper;
import com.eonmind.common.contract.enums.DelEnum;
import com.eonmind.common.provider.entity.knowledge.Knowledge;
import com.eonmind.knowledge.dto.KnowledgeDto;
import com.eonmind.user.contract.dto.UserInfoData;
import com.mongoplus.conditions.query.QueryWrapper;
import com.mongoplus.conditions.update.UpdateWrapper;
import com.mongoplus.model.PageResult;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author: AKang
 * @CreateTime: 2025-05-09
 */
@Component
public class KnowledgeMapper extends BaseMongoMapper<Knowledge> {

    @Resource
    private KnowledgeUploadFileMapper knowledgeUploadFileMapper;

    /**
     * 根据知识库名称查询知识库
     *
     * @param name
     * @param id
     */
    public Knowledge getKnowledgeByName(String name, Long id) {
        QueryWrapper<Knowledge> queryWrapper = createMgoQuery()
                .eq(Knowledge::getName, name)
                .eq(Knowledge::getUserId, id)
                .eq(Knowledge::getDel, DelEnum.UN_DEL.getCode());
        Knowledge knowledge = one(queryWrapper);
        return knowledge;
    }


    /**
     * 创建知识库
     *
     * @param knowledge
     */
    public void saveKnowledge(Knowledge knowledge) {
        save(knowledge);
    }

    /**
     * 更新知识库
     *
     * @param knowledge
     */
    public void updateKnowledge(Knowledge knowledge) {
        UpdateWrapper<Knowledge> updateWrapper = createMgoUpdate()
                .eq(Knowledge::getId, knowledge.getId())
                .set(ObjectUtils.isNotEmpty(knowledge.getName())
                        , Knowledge::getName, knowledge.getName())
                .set(ObjectUtils.isNotEmpty(knowledge.getDesc())
                        , Knowledge::getDesc, knowledge.getDesc())
                .set(ObjectUtils.isNotEmpty(knowledge.getKnowledgeType())
                        , Knowledge::getKnowledgeType, knowledge.getKnowledgeType())
                .set(ObjectUtils.isNotEmpty(knowledge.getUpdateTime())
                        , Knowledge::getUpdateTime, knowledge.getUpdateTime());
        update(updateWrapper);
    }

    /**
     * 删除知识库
     *
     * @param knowledgeDeleteRequest
     */
    public void deleteKnowledge(KnowledgeDto.KnowledgeDeleteRequest knowledgeDeleteRequest, UserInfoData userInfoData) {
        UpdateWrapper<Knowledge> deleteWrapper = createMgoUpdate()
                .eq(Knowledge::getId, knowledgeDeleteRequest.getKnowledgeId())
                .eq(Knowledge::getUserId, userInfoData.getId())
                .set(Knowledge::getDel, DelEnum.DEL.getCode());
        update(deleteWrapper);
    }


    /**
     * 分页查询知识库
     *
     * @param pageRequest
     * @return PageResult<Knowledge>
     */
    public PageResult<KnowledgeDto.KnowledgeResponse> listKnowledge(UserInfoData userInfoData, KnowledgeDto.KnowledgePageRequest pageRequest) {
        if (ObjectUtils.isEmpty(pageRequest)) {
            return new PageResult<>();
        }
        QueryWrapper<Knowledge> mgoQuery = createMgoQuery()
                .eq(Knowledge::getUserId, userInfoData.getId())
                .likeLeft(StringUtils.isNotBlank(pageRequest.getKeyword()), Knowledge::getName, pageRequest.getKeyword())
                .eq(Knowledge::getDel, DelEnum.UN_DEL.getCode());
        PageResult<Knowledge> pageResult = page(mgoQuery, pageRequest.getPage());

        // 封装文档数目
        List<KnowledgeDto.KnowledgeResponse> responseList = new ArrayList<>();
        for (Knowledge knowledge : pageResult.getContentData()) {
            KnowledgeDto.KnowledgeResponse response = new KnowledgeDto.KnowledgeResponse();
            response.setId(knowledge.getId());
            response.setName(knowledge.getName());
            response.setDesc(knowledge.getDesc());
            response.setKnowledgeType(knowledge.getKnowledgeType());
            // 查询文档数目
            Long documentCount = knowledgeUploadFileMapper.getKnowDocumentCount(knowledge.getId());
            response.setDocumentCount(documentCount);
            responseList.add(response);
        }

        // 重新封装分页结果
        PageResult<KnowledgeDto.KnowledgeResponse> responsePageResult = new PageResult<>();
        responsePageResult.setContentData(responseList);
        responsePageResult.setContentData(responseList);
        responsePageResult.setPageNum(pageResult.getPageNum());
        responsePageResult.setPageSize(pageResult.getPageSize());
        responsePageResult.setTotalSize(pageResult.getTotalSize());
        responsePageResult.setTotalPages(pageResult.getTotalPages());
        responsePageResult.setFirstPage(pageResult.isFirstPage());
        responsePageResult.setLastPage(pageResult.isLastPage());
        responsePageResult.setHasPreviousPage(pageResult.isHasPreviousPage());
        responsePageResult.setHasNextPage(pageResult.isHasNextPage());

        return responsePageResult;
    }

    /**
     * 根据知识库id查询百炼知识库IndexId
     *
     * @param knowledgeId
     * @return Knowledge
     */
    public String getBailianKnowledgeIndexId(Long knowledgeId) {
        QueryWrapper<Knowledge> queryWrapper = createMgoQuery()
                .eq(Knowledge::getId, knowledgeId)
                .eq(Knowledge::getDel, DelEnum.UN_DEL.getCode());
        Knowledge knowledge = one(queryWrapper);
        return knowledge.getIndexId();
    }

    /**
     * 根据indexId查询indexName
     *
     * @param indexId
     * @return String
     */
    public String getIndexNameByIndexId(String indexId) {
        QueryWrapper<Knowledge> queryWrapper = createMgoQuery()
                .eq(Knowledge::getIndexId, indexId)
                .eq(Knowledge::getDel, DelEnum.UN_DEL.getCode());
        return one(queryWrapper).getIndexName();
    }

    /**
     * 根据indexId查询KnowledgeId
     *
     * @param indexId
     * @return Long
     */
    public Long getKnowledgeIdByIndexId(String indexId) {
        QueryWrapper<Knowledge> queryWrapper = createMgoQuery()
                .eq(Knowledge::getIndexId, indexId)
                .eq(Knowledge::getDel, DelEnum.UN_DEL.getCode());
        return one(queryWrapper).getId();
    }

    /**
     * 根据知识库id和用户id查询知识库,用于判断该用户是否是该知识库的拥有者
     *
     * @param knowledgeId
     * @param userId
     * @return Knowledge
     */
    public Knowledge getKnowledgeByKnowledgeIdAndUserId(Long knowledgeId, Long userId) {
        QueryWrapper<Knowledge> queryWrapper = createMgoQuery()
                .eq(Knowledge::getId, knowledgeId)
                .eq(Knowledge::getUserId, userId)
                .eq(Knowledge::getDel, DelEnum.UN_DEL.getCode());
        return one(queryWrapper);
    }

    /**
     * 根据indexId查询userId
     *
     * @param IndexId
     * @return Long
     */
    public Long getUserIdByIndexId(String IndexId) {
        QueryWrapper<Knowledge> queryWrapper = createMgoQuery()
                .eq(Knowledge::getIndexId, IndexId)
                .eq(Knowledge::getDel, DelEnum.UN_DEL.getCode());
        return one(queryWrapper).getUserId();
    }

    public Knowledge getKnowledgeById(Long id) {
        QueryWrapper<Knowledge> eq = createMgoQuery()
                .eq(Knowledge::getId, id)
                .eq(Knowledge::getDel, DelEnum.UN_DEL.getCode());
        return one(eq);
    }
}
